package com.elder.business.service.impl;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.elder.business.domain.OrderStatistics;
import com.elder.business.mapper.OrderStatisticsMapper;
import com.elder.business.service.IOrderStatisticsService;
import com.elder.common.core.page.TableDataInfo;
import com.elder.common.utils.DateUtils;
import com.elder.common.utils.IntegerUtils;
import com.elder.common.utils.StringNewUtils;
import com.elder.common.utils.uuid.SnowGenerator;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author elder
 * @date 2024-03-17
 */
@Service
public class OrderStatisticsServiceImpl implements IOrderStatisticsService
{
    @Autowired
    private OrderStatisticsMapper orderStatisticsMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public OrderStatistics selectOrderStatisticsById(Long id)
    {
        return orderStatisticsMapper.selectOrderStatisticsById(id);
    }

    /**
     * 列表
     */
    @Override
    public TableDataInfo selectOrderStatisticsList(Integer pageNum, Integer pageSize) {
        List<OrderStatistics> statisticsList = orderStatisticsMapper.selectOrderStatisticsList(new OrderStatistics());
        List<JSONObject> objectList = statisticsList.stream().map(v -> {
            JSONObject obj = new JSONObject();
            obj.put("id", StringNewUtils.formatStr(v.getId()));
            obj.put("orderDate", DateUtils.dateStr(v.getOrderDate()));
            obj.put("totalOrders", v.getTotalOrders());
            obj.put("totalAmount", v.getTotalAmount());
            return obj;
        }).collect(Collectors.toList());
        TableDataInfo data = new TableDataInfo();
        data.setRows(objectList);
        return data;
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param orderStatistics 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertOrderStatistics(OrderStatistics orderStatistics)
    {
        return orderStatisticsMapper.insertOrderStatistics(orderStatistics);
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param orderStatistics 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateOrderStatistics(OrderStatistics orderStatistics)
    {
        return orderStatisticsMapper.updateOrderStatistics(orderStatistics);
    }

    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOrderStatisticsByIds(Long[] ids)
    {
        return orderStatisticsMapper.deleteOrderStatisticsByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteOrderStatisticsById(Long id)
    {
        return orderStatisticsMapper.deleteOrderStatisticsById(id);
    }

    @Override
    public Integer updateOrderStatisticsInfo(Long monthStartTime, String orderNum, String totalAmount) {
        OrderStatistics orderStatistics = orderStatisticsMapper.getOrderStatisticsMonth(monthStartTime);
        if(Objects.isNull(orderStatistics)){
            orderStatistics = new OrderStatistics();
            orderStatistics.setId(SnowGenerator.getId());
            orderStatistics.setOrderDate(monthStartTime);
            orderStatistics.setTotalOrders(orderNum);
            orderStatistics.setTotalAmount(totalAmount);
            orderStatistics.setExpensesAmount("0");
            return orderStatisticsMapper.insertOrderStatistics(orderStatistics);
        }else {
            orderStatistics.setTotalOrders(orderNum);
            orderStatistics.setTotalAmount(totalAmount);
            return orderStatisticsMapper.updateOrderStatistics(orderStatistics);
        }
    }


    /***
     * @description 获取订单统计信息 （用于折线图展示）
     * @return JSONObject
     * @author zyk
     * @date 2024/3/20 16:14
     */
    @Override
    public JSONObject getOrderStatisticsInfo() {
        List<String> dateYear = dateYear();
        List<OrderStatistics> statisticsList = orderStatisticsMapper.getOrderStatisticsInfo();
        Map<String,OrderStatistics> orderMap = CollectionUtils.isEmpty(statisticsList)?new HashMap<>():getOrderStatisticsMap(statisticsList);
//        Integer[] totalAmount = {0,0};
//        if(CollectionUtils.isNotEmpty(statisticsList)){
//            statisticsList.stream().map(v->{
//                orderMap.put(DateUtils.dateYearMonth(v.getOrderDate()),v);
//                totalAmount[0] = totalAmount[0] + IntegerUtils.toInteger(v.getTotalAmount());
//                totalAmount[1] = totalAmount[1] + IntegerUtils.toInteger(v.getExpensesAmount());
//                return v;
//            });
//        }
        JSONObject order = new JSONObject();
        JSONArray array = new JSONArray();
        Double totalAmount = 0.0;
        Double expenditure = 0.0;
        for(String date:dateYear){
            order = new JSONObject();
            order.put("month",date);
            if(Objects.isNull(orderMap.get(date))){
                order.put("earningAmount",0);
                order.put("orderNum",0);
                order.put("expensesAmount",0);
            }else {
                order.put("earningAmount",StringNewUtils.formatStr(orderMap.get(date).getTotalAmount()));
                order.put("orderNum",Objects.isNull(orderMap.get(date))?0:orderMap.get(date).getTotalOrders());
                order.put("expensesAmount",StringNewUtils.formatStr(orderMap.get(date).getExpensesAmount()));
                totalAmount+=Double.parseDouble(orderMap.get(date).getTotalAmount());
                expenditure+= Double.parseDouble(orderMap.get(date).getExpensesAmount());
            }
            array.add(order);
        }
        JSONObject result = new JSONObject();
        result.put("code",200);
        result.put("data",array);
        result.put("totalIncome",StringNewUtils.double2Str(totalAmount));
        result.put("totalExpenditure",StringNewUtils.double2Str(expenditure));
        return result;
    }


    public Map<String,OrderStatistics> getOrderStatisticsMap(List<OrderStatistics> orderStatisticsList) {
        Map<String,OrderStatistics> map = new HashMap<>();
        for(OrderStatistics order: orderStatisticsList){
            map.put(DateUtils.dateYearMonth(order.getOrderDate()),order);
        }
        return map;
    }
    public static List<String> dateYear() {
        List<String> dates = new ArrayList<>();
        LocalDate currentDate = LocalDate.now();
        // 获取当前日期的前一年日期
        LocalDate oneYearAgo = currentDate.minusYears(1);

        // 使用 DateTimeFormatter 格式化日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");

        // 输出近一年内每个月的日期
        while (oneYearAgo.isBefore(currentDate) || oneYearAgo.isEqual(currentDate)) {
            String formattedDate = oneYearAgo.format(formatter);
            dates.add(formattedDate);
            oneYearAgo = oneYearAgo.plusMonths(1);
        }
        return dates;
    }

    /***
     * @description  更新支出信息
     * @param monthStartTime
     * @param totalAmount
     * @return Integer
     * @author zyk
     * @date 2024/3/20 20:24
     */
    @Override
    public Integer updateOrderInfo(Long monthStartTime, String totalAmount) {
        OrderStatistics orderStatistics = orderStatisticsMapper.getOrderStatisticsMonth(monthStartTime);
        if(Objects.isNull(orderStatistics)){
            orderStatistics = new OrderStatistics();
            orderStatistics.setId(SnowGenerator.getId());
            orderStatistics.setOrderDate(monthStartTime);
            orderStatistics.setTotalOrders("0");
            orderStatistics.setTotalAmount("0");
            orderStatistics.setExpensesAmount(totalAmount);
            return orderStatisticsMapper.insertOrderStatistics(orderStatistics);
        }else {
            orderStatistics.setExpensesAmount(totalAmount);
            return orderStatisticsMapper.updateOrderStatistics(orderStatistics);
        }
    }
}
